#include <iostream>
using std::cout;
using std::endl;

class Singleton{
    friend class AutoRelease;

public:
    static Singleton* getInstance(){
        pthread_once(&_once, init);
        return _pInstance;
    }


    void print() { cout << "Singleton working" << endl; } // 示例方法

private:
    static void init(){
        if(_pInstance == nullptr){
            _pInstance = new Singleton();
            static AutoRelease ar(_pInstance);  // 托管指针
            cout << "getInstance" << endl;
        }
    }

    static void destroy(){
        if(_pInstance != nullptr){
            delete _pInstance;
            _pInstance = nullptr;
            cout << "getInstance" << endl;
        }
    }

    // 私有类
    class AutoRelease{
    public:
        AutoRelease(Singleton* ptr)
            :_ptr(ptr){
                cout << "AutoRelease" << endl;
            }

        ~AutoRelease(){
            if(_ptr != nullptr){
                delete _ptr;    // 此处间接访问了singleton的私有成员，需要添加友元
                _ptr = nullptr;

                cout << "~AutoRelease" << endl;
            }
        }

        // 智能指针属于包装器重载，其它运算符应由Singleton自己重载
        Singleton* operator->(){
            return _ptr;
        }

        Singleton& operator*(){
            return *_ptr;
        }

    private:
        Singleton* _ptr;
    };
    static Singleton *_pInstance;
    static pthread_once_t _once;

    // 构造与析构函数
    Singleton() = default;  // 只定义不实现会报错
    ~Singleton() = default;

    // 删除非单例函数
    Singleton(const Singleton&) = delete;
    Singleton operator=(const Singleton&) = delete;
};

// 初始化静态成员
Singleton* Singleton::_pInstance = nullptr;
pthread_once_t Singleton::_once = PTHREAD_ONCE_INIT;

void test(){
    Singleton::getInstance()->print();
    Singleton::getInstance()->print();

//    AutoRelease ar(Singleton::getInstance());
}

int main()
{
    test();
    return 0;
}

